const DEFAULT_BASE_URL = 'http://localhost:6002'

// 在开发环境中使用相对路径，让Vite代理处理
const BASE_URL = import.meta.env.VITE_API_BASE || (import.meta.env.DEV ? '' : DEFAULT_BASE_URL)

function buildUrl(path, params) {
  // 在开发环境中直接使用相对路径
  if (import.meta.env.DEV && !import.meta.env.VITE_API_BASE) {
    const url = new URL(path, window.location.origin)
    if (params && typeof params === 'object') {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          url.searchParams.append(key, String(value))
        }
      })
    }
    return url.toString()
  }
  
  const url = new URL(path, BASE_URL)
  if (params && typeof params === 'object') {
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        url.searchParams.append(key, String(value))
      }
    })
  }
  return url.toString()
}

export async function request(path, { method = 'GET', headers = {}, params, body } = {}) {
  const url = buildUrl(path, params)
  const finalHeaders = { 'Content-Type': 'application/json', ...headers }
  
  // 添加调试信息
  console.log('请求URL:', url)
  console.log('请求方法:', method)
  console.log('请求头:', finalHeaders)
  console.log('请求体:', body)

  const response = await fetch(url, {
    method,
    headers: finalHeaders,
    body: body ? JSON.stringify(body) : undefined,
  })

  if (!response.ok) {
    // 尝试解析JSON错误响应
    try {
      const errorData = await response.json()
      if (errorData && errorData.message) {
        // 如果后端返回了错误信息，创建一个包含状态码和消息的错误对象
        const error = new Error(errorData.message)
        error.status = response.status
        error.data = errorData
        throw error
      } else {
        // 如果后端没有返回message，使用状态码信息
        const error = new Error(`Request failed ${response.status}`)
        error.status = response.status
        error.data = errorData
        throw error
      }
    } catch (parseError) {
      // 如果无法解析JSON，使用原始错误信息
      const text = await response.text().catch(() => '')
      const error = new Error(`Request failed ${response.status}: ${text || response.statusText}`)
      error.status = response.status
      throw error
    }
  }

  const contentType = response.headers.get('content-type') || ''
  if (contentType.includes('application/json')) {
    return await response.json()
  }
  return await response.text()
}

export function get(path, params, options = {}) {
  return request(path, { ...options, method: 'GET', params })
}

export function post(path, body, options = {}) {
  return request(path, { ...options, method: 'POST', body })
}

export function put(path, body, options = {}) {
  return request(path, { ...options, method: 'PUT', body })
}

export function del(path, options = {}) {
  return request(path, { ...options, method: 'DELETE' })
}

export const apiBaseUrl = BASE_URL


